<template>
  <el-select
    :value="value"
    :placeholder="placeholder"
    :clearable="clearable"
    filterable
    @change="onChange"
  >
    <el-option
      v-for="item of flattenOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      :style="{ paddingLeft: paddingLeft(item) }"
    />
  </el-select>
</template>

<script>
import { Select } from 'element-ui'

const flattenOptions = (options, indent = 1) => {
  const fo = []
  options.forEach((o) => {
    o.indent = indent
    fo.push(o)
    if (Array.isArray(o.children)) {
      fo.push(...flattenOptions(o.children, indent + 1))
    }
  })

  return fo
}

export default {
  name: 'AdminTreeSelect',
  props: {
    ...Select.props,
    options: {
      type: Array,
      required: true,
    },
  },
  computed: {
    flattenOptions() {
      return flattenOptions(this.options)
    },
  },
  methods: {
    onChange(value) {
      this.$emit('input', value)
    },
    paddingLeft(item) {
      return `${item.indent * 20}px`
    },
  },
}
</script>
